﻿#region License
// Copyright © 2004 - 2010 All Right Reserved, Derek Goslin
// 
// 1. Definitions
// The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under U.S. copyright law.
// A "contribution" is the original software, or any additions or changes to the software.
// A "contributor" is any person that distributes its contribution under this license.
// "Licensed patents" are a contributor's patent claims that read directly on its contribution.
// 
// 2. Grant of Rights
// (A) Copyright Grant- Subject to the terms of this license, including the license
//     conditions and limitations in section 3, each contributor grants you a non-exclusive,
//     worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative 
//     works of its contribution, and distribute its contribution or any derivative works that you create.
// (B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations
//     in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its
//     licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of
//     its contribution in the software or derivative works of the contribution in the software.
// 
// 3. Conditions and Limitations
// (A) Reciprocal Grants- For any file you distribute that contains code from the software (in source code or binary format), 
//     you must provide recipients the source code to that file along with a copy of this license, which license will govern that file. 
//     You may license other files that are entirely your own work and do not contain code from the software under any terms you choose.
// (B) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks.
// (C) If you bring a patent claim against any contributor over patents that you claim are infringed by the software,
//     your patent license from such contributor to the software ends automatically.
// (D) If you distribute any portion of the software, you must retain all copyright, patent, trademark,
//     and attribution notices that are present in the software.
// (E) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy 
//     of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do 
//     so under a license that complies with this license.
// (F) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions.
//    You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your
//    local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement.
#endregion

using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using DnEcuDiag.Exceptions;

namespace DnEcuDiag.Forms
{
    /// <summary>
    /// Summary description for AboutForm.
    /// </summary>
    public partial class AboutForm : Form
    {
        private delegate void LaunchUrlDelegate(String target);

        Image _backgroundImage;
        private const double ImageScale = 0.5;
        readonly Color _realTransparencyColor = Color.White;

        Label _versionLabel;
        Label _copyrightLabel;
        LinkLabel _urlLabel;

        private const string ResourceNamespace = "DnEcuDiag.Images.";

        // There are 2 kinds of transparency:
        // 1) The transparency copies the current background (other dialogs/desktop) and shows this so it looks transparent
        //    but isn't. This allows shadow-like images, that is from 0% to 100% transparent. However this way fails to update 
        //    the transparent part properly when other dialogs move over it, or the background changes.
        // 2) "Real" transparency. This way a color is specified and that color will be shown transparent. So shadow-like images
        //    are not possible. The shadow will not be transparent, but will be blended with the transparency color. (glow-like)
        //
        // Set UseRealTransparency to true when you want to use the second option.

        public AboutForm()
        {
            Initialize();
        }

        public void OnClose(object sender, EventArgs e)
        {
            Close();
        }

        public static Stream GetResourceStream(string resourceName)
        {
            Assembly assembly = Assembly.GetAssembly(typeof(AboutForm));
            if (assembly.GetManifestResourceInfo(ResourceNamespace + resourceName) == null)
            {
                throw new ResourceNotFoundException("Could not find resource: " + ResourceNamespace + resourceName);
            }

            Stream resourceStream = assembly.GetManifestResourceStream(ResourceNamespace + resourceName);
            if (resourceStream == null)
            {
                throw new ResourceNotFoundException("Could not load resource: " + ResourceNamespace + resourceName);
            }

            return resourceStream;
        }

        private void Initialize()
        {
            Font = new Font("Tahoma", 8.25F, FontStyle.Regular, GraphicsUnit.Point, 0);

            StartPosition = FormStartPosition.CenterParent;
            FormBorderStyle = FormBorderStyle.None;
            ShowInTaskbar = false;

            Width = 320;
            Height = 160;

            _backgroundImage = Image.FromStream(GetResourceStream("About.png"));

            const int labelHeight = 16;

            _versionLabel = new Label
                               {
                                   Text = String.Format(CultureInfo.InvariantCulture, WinFormStrings.VersionFormatString, Assembly.GetExecutingAssembly().GetName().Version),
                                   Left = 70,
                                   Top = 86,
                                   Width = 300,
                                   Height = labelHeight,
                                   BackColor = Color.Transparent
                               };

            _versionLabel.Click += OnClose;

            Controls.Add(_versionLabel);

            _copyrightLabel = new Label
                                 {
                                     Text = String.Format(WinFormStrings.Copyright, DateTime.Now.Year),
                                     Left = 70,
                                     Top = (_versionLabel.Top + _versionLabel.Height),
                                     Width = 300,
                                     Height = labelHeight,
                                     BackColor = Color.Transparent
                                 };
            _copyrightLabel.Click += OnClose;

            Controls.Add(_copyrightLabel);

            _urlLabel = new LinkLabel
                            {
                                Text = WinFormStrings.HttpApplicationUrl,
                                Left = 70,
                                Top = _copyrightLabel.Top + _copyrightLabel.Height,
                                Width = 160,
                                Height = labelHeight,
                                BackColor = Color.Transparent
                            };

            _urlLabel.Links.Add(0, WinFormStrings.HttpApplicationUrl.Length, WinFormStrings.HttpApplicationUrl);
            _urlLabel.LinkClicked += OnUrlClicked;

            Controls.Add(_urlLabel);

            Click += OnClose;

            // Make the background color of form display transparently.
            // The image with the semi transparant stuff, will use this color (glow-like)
            BackColor = _realTransparencyColor;
            TransparencyKey = BackColor;
    }

        private void OnUrlClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            _urlLabel.Links[_urlLabel.Links.IndexOf(e.Link)].Visited = true;

            var target = e.Link.LinkData as String;

            LaunchUrlDelegate launchUrlDelegate = LaunchUrl;

            launchUrlDelegate(target);
        }

        private static void LaunchUrl(String target)
        {
            // Navigate to it.
            try
            {
                Process.Start(target);
            }
            catch (Win32Exception)
            {
                // Workaround for:
                // "Win32Exception: The requested lookup key was not found in any active activation context"   
                var process = new Process {StartInfo = {FileName = "cmd.exe", Arguments = "/c start " + target, CreateNoWindow = true, UseShellExecute = false}};
                process.Start();
            }
        }

        protected override void OnPaintBackground(PaintEventArgs e)
        {
            if (_backgroundImage != null)
            {
                Graphics gfx = e.Graphics;
                gfx.Clear(_realTransparencyColor);
                gfx.DrawImage(_backgroundImage, new Rectangle(0, 0,
                                                             (int)Math.Round(_backgroundImage.Width * ImageScale),
                                                             (int)Math.Round(_backgroundImage.Height * ImageScale)));
            }
        }
    }
}